package com.example.pageexample.base;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.paging.PagedListAdapter;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.example.pageexample.R;
import com.example.pageexample.database.Picture;

import java.util.List;

/**
 * Paging控件Adapter基类
 * @author mailanglideguozhe
 * @date 20210621
 * @param <T>
 */
public abstract class BaseAdapter<T> extends PagedListAdapter<T , BaseAdapter.ViewHolder> {
    private static final String TAG = "BaseAdapter";
    private List<T> dataList;

    public BaseAdapter() {
        super(DIFF_CALLBACK);
    }

    public void setDataList(List<T> dataList) {
        this.dataList = dataList;
        notifyDataSetChanged();
    }

    public List<T> getDataList() {
        return dataList;
    }

    @NonNull
    @Override
    public BaseAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(getLayoutId(),null);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull BaseAdapter.ViewHolder holder, int position) {
        if(null != dataList && null != dataList.get(position)){
            setViewData(holder , position, getItem(position));
        }
        holder.itemView.setTag(position);
    }

    @Override
    public void onBindViewHolder(@NonNull BaseAdapter.ViewHolder holder, int position, @NonNull List<Object> payloads) {
        super.onBindViewHolder(holder, position, payloads);
        setViewData(holder , position, getItem(position));
    }

    //由实现类完成视图的初始化和赋值
    public abstract void setViewData(ViewHolder holder , int pos, T t);

    //由实现类指定布局
    public abstract int getLayoutId();

    /**
     * 对象数据的比较
     */
    private static DiffUtil.ItemCallback DIFF_CALLBACK = new DiffUtil.ItemCallback<Picture>() {
        @Override
        public boolean areItemsTheSame(@NonNull Picture oldItem, @NonNull Picture newItem) {
            Log.d(TAG,"areItemsTheSame = "+(oldItem.id ==  newItem.id));
            return oldItem.id ==  newItem.id;
        }

        @Override
        public boolean areContentsTheSame(@NonNull Picture oldItem, @NonNull Picture newItem) {
            Log.d(TAG,"areContentsTheSame = "+oldItem.name.equals(newItem.name));
            return oldItem.name.equals(newItem.name);
        }
    };

    public class ViewHolder extends RecyclerView.ViewHolder{
        public ImageView imageView;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.imageview);
        }
    }
}
